<?php
if (!defined("BASEPATH")) exit("No direct script access allowed");

class Odds_model extends MY_Model {

	function __construct() {
		parent::__construct();
		$this->tableName = "odds";
		$this->prefix = "odds";
	}

	function clearOdds() {
		$this->db->query("truncate ".$this->tableName);
	}
	
	function tableFix() {
		$qs =	"
				update
					odds
				set
					odds_team1 = if(odds_team1 > odds_team2, odds_team2, odds_team1),
					odds_team2 = if(odds_team1 > odds_team2, odds_team1, odds_team2),
					odds_odds1 = if(odds_team1 > odds_team2, odds_odds2, odds_odds1),
					odds_odds2 = if(odds_team1 > odds_team2, odds_odds1, odds_odds2)
				";
		$this->db->query($qs);
	}
	
	function mapping() {
		$qs =	"
				update
					odds
					left join mapping as m on m.map_child_name = odds_team1
					left join mapping as mm on mm.map_child_name = odds_team2
				set
					odds_team1_map_id = if(m.map_child_name = odds_team1, m.map_id, null),
					odds_team2_map_id = if(mm.map_child_name = odds_team2, mm.map_id, null)
				where
					odds_team1_map_id is null or odds_team2_map_id is null
				";
		$this->db->query($qs);
	}
	
	function getUnmappedElements() {
		$qs =	"
				select 
					tt.element, count(*) as cnt
				from
					(
					select
						odds_team1 as element
					from
						odds
					where
						odds_del = 0 and odds_team1_map_id is null
					union all
					select
						odds_team2 as element
					from
						odds
					where
						odds_del = 0 and odds_team2_map_id is null
					) as tt
				group by
					tt.element
				order by
					cnt desc, length(tt.element) desc, tt.element
				";
		$result = $this->db->query($qs);
		//Common::pr($this->db->last_query()); exit;
		if($result->num_rows()) {
			return ($result->result_array());
		}
		return array();
	}
	
	function getArbs() {
		$qs =	"
				select
					odds_team1, m.map_group_name as map_group_name1, odds_team2,  mm.map_group_name as map_group_name2, count(distinct odds_id) as cnt, max(odds_odds1) as max1, max(odds_odds3) as max3, 100*(1-(1/max(odds_odds1) + 1/max(odds_odds3))) as calc
				from
					odds
					join mapping as m on m.map_id = odds_team1_map_id and m.map_del = 0
					join mapping as mm on mm.map_id = odds_team2_map_id and mm.map_del = 0
				group by
					m.map_group_name, mm.map_group_name
				having
					calc > 0
				order by
					calc desc
				";
		$result = $this->db->query($qs);
		//Common::pr($this->db->last_query()); exit;
		if($result->num_rows()) {
			return ($result->result_array());
		}
		return array();
	}
	
}